//
//  MessagePlug.m
//  Chamleon-template
//
//  Created by james on 15/8/28.
//
//

#import "MessagePlug.h"
#import <MessageUI/MessageUI.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "NSData+Base64Additions.h"
#import "MessageSingleton.h"
//#define kEmailAccout @"zhuzhipeng@foreveross.com"
//#define kEmailPassword @"*******"
//#define kEmailserver @"smtp.mxhichina.com"
//#define kEmailServrPort 465

@interface  MessagePlug()
{
    MFMessageComposeViewController *messageComposer;
    MessageSingleton *me;
}

@property (nonatomic,strong) NSString* to;//收件人信息
@property (nonatomic,strong) NSString* cc;// 抄送人信息
@property (nonatomic,strong) NSString* bcc ;// 暗送人信息
@property (nonatomic,strong) NSString* subject;// 发送消息主题
@property (nonatomic,strong) NSString* body;// 发送消息内容
@property (nonatomic,strong) NSString* bodyType;// 发送消息内容类型
@property (nonatomic,strong) NSString* silent;// 是否采用静默方式发送消息


@property (nonatomic,strong) NSString *messageCallBackId;//存储消息callbackid(因为是单例，只有一个)
@property (nonatomic,strong) NSMutableDictionary *emailDic;//存储邮件callbackid

@end


@implementation MessagePlug


//设置邮箱发件人信息
-(void)setEmailSenderInfo:(CDVInvokedUrlCommand*)command{
    NSDictionary *para=[command.arguments firstObject];
   
    NSArray *Array=[para allKeys];
    if ([Array containsObject:@"senderEmailAcount"]&&[Array containsObject:@"senderEmailPassword"]&&[Array containsObject:@"senderEmailServer"]) {
        
    }else{
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"缺少参数"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    
    }
    [self.commandDelegate runInBackground: ^{
        me=[[MessageSingleton alloc]init];
        me.senderEmailAcount=para[@"senderEmailAcount"];
        me.senderEmailPassword=para[@"senderEmailPassword"];
        me.senderEmailPort=[para[@"senderEmailPort"] intValue];
        me.senderEmailServer=para[@"senderEmailServer"];
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"设置正确"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

    }];

}
//发送短信
-(void)sendMessage:(CDVInvokedUrlCommand*)command{
    [self.commandDelegate runInBackground: ^{

    
     NSDictionary *para=[command.arguments firstObject];
    self.messageCallBackId=command.callbackId;
        
      if([MFMessageComposeViewController canSendText])
    {
        if (messageComposer) {
            messageComposer = nil;
            messageComposer = [[MFMessageComposeViewController alloc]init];
        }
        messageComposer=[[MFMessageComposeViewController alloc] init];
        
        //设置委托
        messageComposer.messageComposeDelegate=self;
        
        //短信内容
        messageComposer.body=para[@"body"];
        
        //设置短信收件方
        NSMutableArray *recipientsArray=[NSMutableArray array];
        
        if ([para[@"to"] isKindOfClass:[NSString class]]) {
            NSArray *allArr= [para[@"to"] componentsSeparatedByString:@";"];
            for (NSString *receipt in allArr) {
                if (receipt.length) {
                    [recipientsArray addObject:receipt];
                }
            }
            messageComposer.recipients=recipientsArray;

        }
        [self.viewController presentViewController:messageComposer animated:YES
                         completion:nil];
    }
    else
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Sms Error" message:@"device can not send sms text" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        
    }
    }];
    
}

-(void)sendEmail:(CDVInvokedUrlCommand*)command{
    //中文标题时需要将SKPSMTPMessage.m中改成  NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSDictionary *para=[command.arguments firstObject];
    
//    para=@{@"subject":@"你好，测试用",
//           @"bodyType":@"text/plain",
//           @"body":@"你好，测试用",
//           };
    if (![para isKindOfClass:[NSDictionary class]]) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"参数不存在！"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
    
  MessageSingleton *message=[MessageSingleton sharedInstance];
    
    SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
    testMsg.fromEmail =message.senderEmailAcount;
    
       if (!self.emailDic) {
        self.emailDic=[NSMutableDictionary dictionary];
    }
    [self.emailDic setObject:testMsg forKey:command.callbackId];
    
//    testMsg.toEmail = @"zhuzhipeng@foreveross.com";
//    testMsg.bccEmail = @"651289808@qq.com";
//    testMsg.ccEmail = @"zhuzhipeng1000@163.com";
    testMsg.toEmail =[para[@"to"] isKindOfClass:[NSString class]]?para[@"to"]:@"";
    testMsg.ccEmail=[para[@"cc"] isKindOfClass:[NSString class]]?para[@"cc"]:@"";
    testMsg.bccEmail = [para[@"bcc"] isKindOfClass:[NSString class]]?para[@"bcc"]:@"";
    if ((!testMsg.toEmail.length)&&(!testMsg.ccEmail.length)&&(!testMsg.bccEmail.length)) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"收件人不能为空"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    if ([MessagePlug checkIsAllEmailValidOfString:testMsg.toEmail]&&[MessagePlug checkIsAllEmailValidOfString:testMsg.ccEmail]&&[MessagePlug checkIsAllEmailValidOfString:testMsg.bccEmail]) {
        
    }else{
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"收件人格式错误"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    
    testMsg.relayHost = message.senderEmailServer;
    testMsg.requiresAuth = TRUE;
    
    if (testMsg.requiresAuth) {
        testMsg.login =message.senderEmailAcount;
        testMsg.pass = message.senderEmailPassword;
        
    }
    
    testMsg.wantsSecure = TRUE; // smtp.gmail.com doesn't work without TLS!
    testMsg.subject =para[@"subject"];
    
    // Only do this for self-signed certs!
    // testMsg.validateSSLChain = NO;
    testMsg.delegate = self;
    
    
    
    //文字信息
    NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:para[@"bodyType"],kSKPSMTPPartContentTypeKey,
                               para[@"body"],kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
    
    
      NSString *vcfPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"vcf"];
//     NSString *imgPath = [[NSBundle mainBundle] pathForResource:@"jj" ofType:@"png"];
//     NSString *excelPath =[[NSBundle mainBundle] pathForResource:@"cc" ofType:@"xlsx"];

    NSLog(@"vcfPath%@",vcfPath);
    NSString *attachString=para[@"attach"];
    if (![attachString isKindOfClass:[NSString class]]) {
        return;
    }else{
    attachString = [attachString stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    attachString = [attachString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   
    }
    NSArray *attachPaths=[attachString componentsSeparatedByString:@";"];
//    NSArray *attachPaths=@[vcfPath,imgPath,excelPath];
    NSMutableArray *attach=[NSMutableArray array];
     [attach addObject:plainPart];
    for (NSString *path in attachPaths) {
        NSString *newPath;
        if ( [path containsString:@"file://"]) {
            newPath =[path substringFromIndex:7];
        }else{
            newPath=path;
        }
      NSDictionary *attachDic= [self AttachByPath:newPath];
       NSLog(@"attachDic%@",newPath);
        
        [attach addObject:attachDic];
    }
   
    
         testMsg.parts = attach;
    
        [testMsg send];


}
-(NSDictionary*)AttachByPath:(NSString*)filePath{

   
    NSString *mineName=[self mineNameOfFilepath:filePath];
    NSData *vcfData = [NSData dataWithContentsOfFile:filePath];
    NSString *fileName=[[filePath componentsSeparatedByString:@"/"]lastObject];
    
    NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@;\r\n\tx-unix-mode=0644;\r\n\tname=\"%@\"",mineName,fileName],kSKPSMTPPartContentTypeKey,[NSString stringWithFormat:
                             @"attachment;\r\n\tfilename=\"%@\"",fileName],kSKPSMTPPartContentDispositionKey,[vcfData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
    return vcfPart;
}

-(NSString*)mineNameOfFilepath:(NSString*)filePath{
    
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[filePath pathExtension], NULL);
    
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    NSLog(@"MIMEType%@",MIMEType);
    NSString* strNS = (__bridge NSString *)MIMEType;
    return strNS;
}
#pragma mark MessageDelegate
// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    //    [self dismissModalViewControllerAnimated:YES];
    [self.viewController dismissViewControllerAnimated:controller completion:^{
        
    }];
    
    if (result == MessageComposeResultCancelled){
          NSLog(@"Message sent cancel");
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"短信发送取消"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:_messageCallBackId];
    
    }else if (result == MessageComposeResultSent){
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"短信发送成功"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:_messageCallBackId];
        NSLog(@"Message sent");

    }else{
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"短信发送失败"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:_messageCallBackId];

        NSLog(@"Message failed");
    }
}
#pragma mark emailDelegate
-(void)messageSent:(SKPSMTPMessage *)message{
    NSLog(@"email sent Ok");
    NSArray *keyArray=[_emailDic  allKeys];
    NSString *messageCallBackId;
    for (NSString *callBackId in keyArray) {
        if (_emailDic[@"callBackId"]==message) {
            messageCallBackId=callBackId;
        }
    }
    
    if (messageCallBackId) {
        [_emailDic removeObjectForKey:messageCallBackId];
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"邮件发送成功"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:messageCallBackId];
        
    }
    
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
    
    NSString *info=[NSString stringWithFormat:@"email sent:%@",error.description];
    NSLog(info);
    NSArray *keyArray=[_emailDic  allKeys];
    NSString *messageCallBackId;
    for (NSString *callBackId in keyArray) {
        if (_emailDic[@"callBackId"]==message) {
            messageCallBackId=callBackId;
        }
    }
    if (messageCallBackId) {
        [_emailDic removeObjectForKey:messageCallBackId];
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:messageCallBackId];
        
    }

}
+(BOOL)checkIsAllEmailValidOfString:(NSString *)addresses{

    NSCharacterSet	*splitSet = [NSCharacterSet characterSetWithCharactersInString:@";,"];
 
    if ((addresses != nil) && (![addresses isEqualToString:@""])) {
        if( [addresses rangeOfString:@";"].location != NSNotFound || [addresses rangeOfString:@","].location != NSNotFound ) {
            NSArray *addressParts = [addresses componentsSeparatedByCharactersInSet:splitSet];
            
            for( NSString *address in addressParts ) {
                if (![MessagePlug validateEmail:address]) {
                    return NO;
                }
            }
        }
        else {
            if (![MessagePlug validateEmail:addresses]) {
                return NO;
            }
        }
    }
    return YES;


}


//验证邮箱是否正确 NO验证不正确，yes 验证正确
+(BOOL)validateEmail:(NSString *)aemail{
    if (![aemail isKindOfClass:[NSString class]]||aemail.length==0) {
        return NO;
    }
    
    NSString *email=@"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b";
    NSError *error=NULL;
    
    NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:email options:NSRegularExpressionCaseInsensitive error:&error];
    
    
    NSArray *matches=[regex matchesInString:aemail options:0 range:NSMakeRange(0, aemail.length)];
    
    NSString *tagString=@"";
    for (NSTextCheckingResult *match in matches) {
        
        NSRange matchRange = [match range];
        tagString= [aemail substringWithRange:matchRange];  // 整个匹配串
        
        NSRange r1 = [match rangeAtIndex:1];
        
        if (!NSEqualRanges(r1, NSMakeRange(NSNotFound, 0))) {    // 由时分组1可能没有找到相应的匹配，用这种办法来判断
            
            NSString *tagName = [aemail substringWithRange:r1];
            NSLog(@"tagName:%@",tagName);
            // 分组1所对应的串
        }
        
        NSString *tagValue = [aemail substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        NSLog(@"tagValue:%@",tagValue);
        
    }
    if (tagString.length>0) {
        return YES;
    }
    
    return NO;
}

@end
